<?php
/**
 * @Author: Jaeger
 * @Date:   2015-01-03 17:44:56
 * @Last Modified by:   anchen
 * @Last Modified time: 2015-01-03 17:59:34
 * 这个模块主要是用于从百度服务器取得cookie/token授权.
 */

require 'const.php';
require 'util.php';
require 'net.php';

//ppui_ligintime 这个字段, 是一个随机数.
function get_ppui_logintime()
{
    return rand(52000, 58535);
}
//获取一个cookie - BAIDUID.
//这里, 我们访问百度首页, 返回的response header里面有我们需要的cookie
function get_BAIDUID()
{
    $url = PASSPORT_URL.'?getapi&tpl=mn&apiver=v3&tt='.time().'&class=login&logintype=basicLogin';
    return urlopen($url)->get_response_header('Set-Cookie');
}
/*
	获取一个页面访问的token, 这里需要之前得到的BAIDUID 这个cookie值
	这个token的有效期还不确定.
	返回的数据如下:
	{"errInfo":{"no": "0"},
	 "data": {
	     "rememberedUserName" : "",
	     "codeString" : "",
	     "token" : "xxxxx",
	     "cookie" : "1",
	     "usernametype":"2",
	     "spLogin" : "rate",
	     "disable":"",
	     "loginrecord":{ 'email':[ ], 'phone':[]}
	}}
*/
function get_token($cookie)
{
	$url = PASSPORT_URL.'?getapi&tpl=pp&apiver=v3&tt='.time().'&class=login&logintype=basicLogin';
	$headers = array(
			'Cookie'=>$cookie,
	        'Accept'=>ACCEPT_HTML,
	        'Cache-control'=>'max-age=0'
		);
	$req = urlopen($url,$headers);
	
	$cookie = $req->get_response_header('Set-Cookie');

	$json = $req->get_response_body();
	$json = str_replace("'", '"', $json);
	$json = json_decode($json,true);
	$token = $json['data']['token'];
	return array($cookie,$token);
}
$arr = get_token(get_BAIDUID());
print_r($arr);
/*
   检查登录历史, 可以获得一个Cookie - UBI.
    返回的信息类似于: 
    {"errInfo":{ "no": "0" }, "data": {'displayname':['xxx@163.com']}}
 */
function get_UBI($cookie,$tokens)
{
	$url = PASSPORT_URL.'?loginhistory&token='.$tokens['token'].'&tpl=pp&apiver=v3&tt='.time();
	$headers = array(
			'Cookie'=>$cookie,
	        'Referer'=>REFERER
		);
	return urlopen($url,$headers)->get_response_header('Set-Cookie');
}
// echo get_UBI($arr[0],array('token'=>$arr[1]));
/*
进行登录验证, 主要是在服务器上验证这个帐户的状态.

    如果帐户不存在, 或者帐户异常, 就不需要再进行最后一步的登录操作了.
    这一步有可能需要输入验证码.
    返回的信息如下:
    {"errInfo":{ "no": "0" }, "data": { "codeString" : "", "vcodetype" : "" }}
 */
function check_login($cookie, $tokens, $username)
{
	$url = PASSPORT_URL.'?logincheck&token='.$tokens['token'].'&tpl=mm&apiver=v3&tt='.time().'&username='.urlencode($username).'&isphone=false';
	$headers = array(
			'Cookie'=>$cookie,
	        'Referer'=>REFERER
		);
	$req = urlopen($url,$headers);

	$cookie = $req->get_response_header('Set-Cookie');

	$json = $req->get_response_body();
	$json = str_replace("'", '"', $json);
	$json = json_decode($json,true);

	return array($cookie,$json);
}
// $rt = check_login($arr[0],array('token'=>$arr[1]),'hj.q@qq.com');
// print_r($rt);
/*
获取登录时的验证码图片.

    codeString - 调用check_login()时返回的codeString.
 */
function get_signin_vcode($cookie, $codeString)
{
	$url = PASSPORT_BASE.'cgi-bin/genimage?'.$codeString;
	$headers = array(
			'Cookie'=>$cookie,
	        'Referer'=>REFERER
		);
	$req = urlopen($url,$headers);
	return $req->get_response_body();
}
/*
刷新验证码.

    vcodetype - 在调用check_login()时返回的vcodetype.
 */
function refresh_signin_vcode($cookie, $tokens, $vcodetype)
{
	//TODO:.....
}
/*
获取RSA公钥, 这个用于加密用户的密码
    
    返回的数据如下:
    {"errno":'0',"msg":'',"pubkey":'-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDk\/ufXg3IBW8+h5i8L8NoXUzcN\nMeKrh4zEupGBkyrURIPUXKDFLWjrv4n2j3RpMZ8GQn\/ETcfoIHGBoCUKJWcfcvmi\nG+OkYeqT6zyJasF0OlKesKfz0fGogMtdCQ6Kqq7X2vrzBPL+4SNU2wgU31g\/tVZl\n3zy5qAsBFkC70vs5FQIDAQAB\n-----END PUBLIC KEY-----\n',"key":'lwCISJnvs7HRNCTxpX7vi25bV9YslF2J'}
 */
function get_public_key($cookie, $tokens)
{
	$url = PASSPORT_BASE.'v2/getpublickey?token='.$tokens['token'].'&tpl=pp&apiver=v3&tt='.time();
	$headers = array(
			'Cookie'=>$cookie,
	        'Referer'=>REFERER
		);
	$req = urlopen($url,$headers);
	$json = $req->get_response_body();
	$json = str_replace("'", '"', $json);
	$json = json_decode($json,true);
	return $json;
}
// $rt = get_public_key($arr[0],array('token'=>$arr[1]));
// print_r($rt);
/*
登录验证.
    password   - 使用RSA加密后的base64字符串
    rsakey     - 与public_key相匹配的rsakey
    verifycode - 验证码, 默认为空

    @return (status, info). 其中, status表示返回的状态:
      0 - 正常, 这里, info里面存放的是auth_cookie
     -1 - 未知异常
      4 - 密码错误
    257 - 需要输入验证码, 此时info里面存放着(vcodetype, codeString))
 */
function post_login($cookie, $tokens, $username, $password, $rsakey, $verifycode='',$codestring='')
{
	$url = PASSPORT_LOGIN;
	$data = 'staticpage=https%3A%2F%2Fpassport.baidu.com%2Fstatic%2Fpasspc-account%2Fhtml%2Fv3Jump.html&charset=UTF-8&token='. $tokens['token'].'&tpl=pp&subpro=&apiver=v3&tt='.time().'&codestring='. $codestring.'&safeflg=0&u=http%3A%2F%2Fpassport.baidu.com%2F&isPhone=&quick_user=0&logintype=basicLogin&logLoginType=pc_loginBasic&idc=&loginmerge=true&username='. urlencode($username).'&password='. urlencode($password).'&verifycode='. $verifycode.'&mem_pass=on&rsakey='. $rsakey.'&crypttype=12&ppui_logintime='.get_ppui_logintime().'&callback=parent.bd__pcbs__28g1kg';
	$headers = array(
			'Cookie'=>$cookie,
	        'Accept'=>ACCEPT_HTML,
	        'Referer'=>REFERER,
	        'Connection'=>'Keep-Alive'
		);
	$req = urlopen($url,$headers,$data);
	echo $req->get_response_body();
}